package com.controller;

import com.domain.Blog;
import com.domain.Type;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.service.impl.BlogServiceImpl;
import com.service.impl.TypeServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
public class BlogController {

    @Autowired
    private BlogServiceImpl blogService;
    @Autowired
    private TypeServiceImpl typeService;

    //向首页跳转
    @GetMapping("/home")
    public String home(){
        return "redirect:loadingData";
    }

    //跳转至发布页
    @GetMapping("/newblog")
    public ModelAndView newblog(){
        return new ModelAndView("template/newblog");
    }

    //跳转到修改页面
    @GetMapping("/toupdate")
    public ModelAndView toUpdate(String bid){
        ModelAndView modelAndView = new ModelAndView("template/newblog");
        modelAndView.addObject("update",blogService.selectBlogById(Integer.parseInt(bid)));
        return modelAndView;
    }

    /**
     * 初始化加载页面
     * 获取分页blog数据
     * 获取分类数据
     * 获取hot热门数据
     * 添加数据到Model
     * 返回前端
     */
    @GetMapping("/loadingData")
    public String getBlog(HttpSession session,Model model, Integer pageNum){
        //pageNum为空设置当前为第一页
        if (pageNum == null){
            pageNum = 1;
        }
        //分页
        PageHelper.startPage(pageNum, 3);
        List<Blog> blogs = blogService.findAllBlog();
        PageInfo<Blog> pageInfo = new PageInfo<>(blogs);
        //分类信息
        List<Type> types = typeService.findAllType();
        //热门blog
        hotBlog(model);
        //存储数据
        model.addAttribute("pageInfo",pageInfo);
        session.setAttribute("types",types);
        model.addAttribute("checkType","0");
        model.addAttribute("keyWords","");
        return "home";
    }

    //分页查询
    @GetMapping("/findPage")
    public String findPage(String checkType,String keyWords,Model model,Integer pageNum){
        if (pageNum == null){
            pageNum = 1;
        }
        if (checkType == null || checkType == ""){
            checkType = "0";
        }
        //分页
        PageHelper.startPage(pageNum, 3);
//        PageInfo<Blog> pageInfo = findByTypeOrKeywords(checkType,keyWords);
        List<Blog> blogs = blogService.findAllBlog();
        //判断checkType
        if (!checkType.equals("0")){
            blogs = blogService.findBlogByType(Integer.parseInt(checkType));
        }
        if (keyWords != "" && keyWords != null){
            blogs = blogService.findBlogByKeyWords(keyWords);
            checkType = "0";
        }
        PageInfo<Blog> pageInfo = new PageInfo<>(blogs);
        //热门blog
        hotBlog(model);
        //存储数据
        model.addAttribute("pageInfo",pageInfo);
        model.addAttribute("checkType",checkType);
        model.addAttribute("keyWords",keyWords);
        return  "home";
    }

    //查看Blog详情（id）,访问量+1
    @RequestMapping("/showBlog")
    public String showBlog(Model model,Integer id){
        Blog blog = blogService.findBlogById(id);
        model.addAttribute("blog",blog);
        hotBlog(model);
        return "blog";
    }

    /* ==================后台管理部分===================== */

    //首次打开blogmanage，查询blog信息
    @GetMapping("/blogmanage")
    public ModelAndView blogmanage(Integer pageNum){
        ModelAndView modelAndView = new ModelAndView("template/blogmanage");
        //初始化pageNum
        if (pageNum == null){
            pageNum = 1;
        }
        //分页
        PageHelper.startPage(pageNum, 10);
        List<Blog> blogs = blogService.findAllBlog();
        PageInfo<Blog> pageInfo = new PageInfo<>(blogs);
        //存储数据
        modelAndView.addObject("pageInfo",pageInfo);
        return modelAndView;
    }

    //分页查看(checkType：类型，keyWords：标题)
    @GetMapping("/blogmanagebypage")
    public ModelAndView blogmanageByPage(String checkType,String keyWords,Integer pageNum){
        if (pageNum == null){
            pageNum = 1;
        }
        if (checkType == null || checkType == ""){
            checkType = "0";
        }
        //分页
        PageHelper.startPage(pageNum, 10);
//        PageInfo<Blog> pageInfo = findByTypeOrKeywords(checkType,keyWords);
        List<Blog> blogs = blogService.findAllBlog();
        //判断checkType
        if (!checkType.equals("0")){
            blogs = blogService.findBlogByType(Integer.parseInt(checkType));
        }
        if (keyWords != "" && keyWords != null){
            blogs = blogService.findBlogByTitle(keyWords);
            checkType = "0";
        }
        PageInfo<Blog> pageInfo = new PageInfo<>(blogs);
        ModelAndView modelAndView = new ModelAndView("template/blogmanage");
        modelAndView.addObject("pageInfo",pageInfo);
        modelAndView.addObject("checkType",checkType);
        modelAndView.addObject("keyWords",keyWords);
        return modelAndView;
    }

    //发布blog
    @PostMapping("/createblog")
    public String createBlog(String title, @RequestParam("type") List<String> type, MultipartFile file, String content, Model model){
        //处理上传图片信息
        //获取文件名及后缀
        String fileName = file.getOriginalFilename();
        //重新生成文件名
        fileName = UUID.randomUUID() + "_" + fileName;
        //指定上传文件地址
        String dirPath = "D:\\IDEA_Project\\blog-springboot\\target\\classes\\static\\img\\";
        File filePath = new File(dirPath);
        if (!filePath.exists()){
            filePath.mkdirs();
        }
        try {
            file.transferTo(new File(dirPath + fileName));

            Blog blog = new Blog();
            blog.setBcontent(content);
            blog.setBimg("img/"+fileName);
            blog.setBtitle(title);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String date = " " + simpleDateFormat.format(new Date());
            blog.setCreatetime(date);
            blog.setUpdatetime(date);
            //写入数据到t_blog
            blogService.insertBlog(blog);
            //写入数据到t_l_t
            Map map = new HashMap();
            int bid = blog.getId();
            for (String tid : type) {
                map.put("bid",bid);
                map.put("tid",tid);
                blogService.insertTBT(map);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return "redirect:newblog";
        }
        return "redirect:blogmanage";
    }

    //修改blog
    @PostMapping("/updateblog")
    public String updateBlog(String bid,String title, @RequestParam(value = "type",required = false) List<String> type, MultipartFile file, String content){
        int b_id = Integer.parseInt(bid);
        Blog blog = new Blog();
        blog.setId(b_id);
        String fileName = file.getOriginalFilename();
        if (fileName != null && fileName != "" && fileName.length() > 0){

            fileName = UUID.randomUUID() + "_" + fileName;
            String dirPath = "D:\\IDEA_Project\\blog-springboot\\target\\classes\\static\\img\\";
            File filePath = new File(dirPath);
            try {
                file.transferTo(new File(dirPath + fileName));
                blog.setBimg("img/"+fileName);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (title != null && title != ""){
            blog.setBtitle(title);
        }
        if (content != "" && content != null){
            blog.setBcontent(content);
        }
        if (type != null && type.size() > 0){
            Map map = new HashMap();
            blogService.deleteTBT(b_id);
            for (String tid : type){
                map.put("tid",tid);
                map.put("bid",b_id);
                blogService.insertTBT(map);
            }
        }
        blog.setUpdatetime(" " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        blogService.updateBlog(blog);
        return "redirect:blogmanage";
    }

    //删除blog
    @GetMapping("/deleteblog")
    public String deleteblog(String bid){
        blogService.deleteblog(Integer.parseInt(bid));
        return "redirect:blogmanage";
    }

//    //类型，关键字，分页查询
//    public PageInfo<Blog> findByTypeOrKeywords(String checkType,String keyWords){
//        List<Blog> blogs = blogService.findAllBlog();
//        //判断checkType
//        if (!checkType.equals("0")){
//            System.out.println("checkType:"+checkType);
//            blogs = blogService.findBlogByType(Integer.parseInt(checkType));
//        }
//        if (keyWords != "" && keyWords != null){
//            blogs = blogService.findBlogByKeyWords(keyWords);
//            checkType = "0";
//        }
//        PageInfo<Blog> pageInfo = new PageInfo<>(blogs);
//        return pageInfo;
//    }

    //存储热门blog到model
    public void hotBlog(Model model){
        List<Blog> hotBlogs = blogService.findHotBlog();
        model.addAttribute("hotBlogs",hotBlogs);
    }

}
